﻿using HomagGroup.Base.UI.Windows;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace HomagChina.Nesting.Views
{
    /// <summary>
    /// PartDetailsDialog.xaml 的交互逻辑
    /// </summary>
    public partial class PartDetailsDialog : Dialog
    {
        private PartDetailsDialogViewModel _viewModel;
        private double VerticalOffset;

        public PartDetailsDialog()
        {
            InitializeComponent();
            var RouterDictionary = (Dictionary<string, RouterItemDataModel>)Application.Current.Properties["RouterMap"];
            HomeViewModel homeViewModel = RouterDictionary["1"].userControl.DataContext as HomeViewModel;
            _viewModel = homeViewModel.partDetailsDialogViewModel;
            // 订阅 ViewModel 的事件
            _viewModel.RequestScrollPositionSave += ViewModel_RequestScrollPositionSave;
            _viewModel.RequestScrollPositionRestore += ViewModel_RequestScrollPositionRestore;
        }

        private void ViewModel_RequestScrollPositionSave(object sender, EventArgs e)
        {
            SaveScrollPosition();
        }

        private void ViewModel_RequestScrollPositionRestore(object sender, EventArgs e)
        {
            RestoreScrollPosition();
        }

        private void SaveScrollPosition()
        {
            var scrollViewer = VisualTreeHelperExtensions.FindVisualChild<ScrollViewer>(PartDetailsDialogTable);
            if (scrollViewer != null)
            {
                VerticalOffset = scrollViewer.VerticalOffset;
            }
        }

        private void RestoreScrollPosition()
        {
            var scrollViewer = VisualTreeHelperExtensions.FindVisualChild<ScrollViewer>(PartDetailsDialogTable);
            if (scrollViewer != null)
            {
                scrollViewer.ScrollToVerticalOffset(VerticalOffset);
            }
        }
    }
}